package Finance::NSCC::Insurance::File::Commissions;

use Moose;
extends 'Finance::NSCC::Insurance::File';
use Finance::NSCC::Insurance::Utils qw/trim/;

my $RHEADER = qr/^80(.{4})MSD(.{30})(.{7})(.)(.{16})(.).{136}$/;
my $R81 = qr/^81(.{4})(.{7})(.)(.{16})(.).{169}$/;
my $R82 = qr/^82(.{8})(.{16})(.)(..)(.{20})(.{30})(.{30})(.{20})(.{30})(.{30})(...)(.{8})$/;

sub _process_header {
  my $self = shift;
  my $io = $self->_file_handle;
  my $head_re = ${ $self->blessed .'::RHEADER' }; #XXX
  my $line;
  if ( defined($line = $io->getline) && ( $line =~ /$head_re/) ) {
    $self->file_date( trim($1) );
    $self->nscc_num( trim($2) );
    $self->record_count( $4+0 );
    $self->_test_indicator( $5 eq 'T' ? 1 : 0 );
  } else {
    $self->_error("Premature end on header record");
  }
}


sub _build_records {
  my $self = shift;
  my $io = $self->_file_handle;

  my $record_count = 1;         #header is already processed
  my @records;
  my $line;
  defined($line = $io->getline) && $record_count++;
  while ($line =~ /$R81/) {
    defined($line = $io->getline) && $record_count++;
    while ( my (@m82) = map{ trim $_} ($line =~ /$R82/)) {
      my $commission = {
                        comm_amt => ($m82[1] / 100) * ($m82[2] == 2 ? 1 : -1),
                        nscc_control_num => $m82[7],
                       };
      push(@records, $commission);
      defined($line = $io->getline) && $record_count++;
    }
  }
  my $target = $self->record_count;
  #$self->_error("Record and target count mismatch ($record_count : $target)")
  #  unless $target == $record_count;
  $self->_clear_file_handle;    #close the filehandle
  return \@records;
}



1;
